package com.xbxkj.commen.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbxkj.commen.bean.Dictionaries;
import com.xbxkj.commen.bean.TreeModel;
import com.xbxkj.commen.controller.helper.$;
import com.xbxkj.commen.controller.model.ResultModel;
import com.xbxkj.commen.mapper.DictionariesMapper;
import com.xbxkj.commen.service.DictionariesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 * 字典表 服务实现类
 * </p>
 *
 * @author 张子艺
 * @since 2019-08-19
 */
@Service
@Slf4j
public class DictionariesServiceImpl extends ServiceImpl<DictionariesMapper, Dictionaries> implements DictionariesService {

    @Override
    public List<TreeModel> finDictionariesAjax(Dictionaries dictionaries) {

        List<TreeModel> treeModels = baseMapper.treeData(dictionaries);
        //TreeModels.setId("0");
        // buildTreeData(TreeModels,entities);
        return treeModels;
    }

    @Override
    public ResultModel<?> delData(String id) {
        if(id.equals("1")){
            return $.error("该节点不可删除");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id", id);
        List<Dictionaries> dictionaries = list(queryWrapper);
        if (dictionaries .size()>0) {
            return $.error("该节点下还有数据，不可进行删除操作");
        } else {
          removeById(id);
          return $.success();
        }
    }

    @Override
    public List<Dictionaries> findDicByParentValue(String parentValue) {
       return baseMapper.findDicByParentValue(parentValue);
    }

    /**
     * 递归生成标准树数据
     *
     * @param TreeModel
     * @param dictionaries
     */
    private void buildTreeData(TreeModel TreeModel, List<Dictionaries> dictionaries) {
        //子集节点
        List< TreeModel> childList = new ArrayList<>();
        //循环 数据库的字典表数据
        for (Dictionaries dbData : dictionaries) {
            //如果子节点的pid等于父节点的ID，则说明是父子关系
            if (dbData.getParentId().equals(TreeModel.getId())) {
                // 是父子关系，则将其放入子集节点
                TreeModel child = new TreeModel();
                child.setId(dbData.getId());
                child.setpId(dbData.getParentId());
                child.setName(dbData.getName());
                child.setValue(dbData.getValue());
                childList.add(child);
                //放入最大的实体
                TreeModel.setChildren(childList);
                log.debug(TreeModel.toString());
                // 继续调用递归算法，将当前作为父节点，继续找他的子节点，反复执行。
                buildTreeData(child, dictionaries);
            }
        }
    }

}
